/**
 * @author BelovedLYC
 * @date 2025-06-01
 * @description 获取二维码状态
 */

import {
  getDeviceId,
  getDeviceName,
  getDeviceType,
} from "../../utils/deviceInfo";
import request from "../request";
import type { ApiResponse } from "../request";
import userService from "../../utils/userService";

export interface EmailLoginPostData {
  email: string;
  code: string;
}

export interface EmailLoginResponse {
  avatar: string | null;
  email: string;
  nickname: string;
  status: number;
  uuid: string;
}

export const sendEmailCodeRequest = async (
  email: string
): Promise<ApiResponse> => {
  return request.post("/email/send", { email });
};

export const emailLoginRequest = async (
  data: EmailLoginPostData
): Promise<ApiResponse<EmailLoginResponse>> => {
  console.log("[Email Login] 发送登录请求:", data);

  try {
    // 使用原始axios实例以便直接访问完整响应
    const response = await request.api.post<ApiResponse<EmailLoginResponse>>(
      "/user/login/email/code",
      data,
      {
        headers: {
          "X-Device-Id": getDeviceId(),
          "X-Device-Name": getDeviceName(),
          "X-Device-Type": getDeviceType().toString(),
        },
      }
    );

    // 直接从响应头获取Authorization (如果存在)
    if (response.headers && typeof response.headers === "object") {
      // 尝试各种可能的键名
      const authHeader =
        response.headers["authorization"] ||
        response.headers["Authorization"] ||
        response.headers.authorization ||
        response.headers.Authorization;

      if (authHeader) {
        console.log(
          "[Email Login] 直接从响应头获取到Authorization:",
          authHeader.substring(0, 20) + "..."
        );
        // 使用userService直接设置
        userService.setToken(authHeader);
      } else {
        console.log("[Email Login] 响应头中没有找到Authorization");
      }
    }

    // 标准化API响应
    const apiResponse = {
      code: response.data.code || response.status,
      message: response.data.message || "请求成功",
      data: response.data.data as EmailLoginResponse,
    };

    if (apiResponse.code === 200 && apiResponse.data) {
      console.log("[Email Login] 登录成功，设置用户信息:", apiResponse.data);

      // 设置用户信息
      userService.setUserInfo(apiResponse.data);

      // 手动触发状态刷新，确保所有监听器都能收到通知
      setTimeout(() => {
        userService.refreshState();
        console.log("[Email Login] 已刷新用户状态");
      }, 10);
    }

    return apiResponse;
  } catch (error) {
    console.error("[Email Login] 登录失败:", error);
    throw error;
  }
};
